import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { Task, TaskModification, ExecutionStatus } from '@/types'
import { useAPIService } from '@/services/api'

export const useTaskStore = defineStore('task', () => {
  const apiService = useAPIService()

  // 状态
  const tasks = ref<Map<string, Task>>(new Map())
  const sessionTasks = ref<Map<string, string[]>>(new Map()) // sessionId -> taskIds
  const currentSessionId = ref<string | null>(null)
  const executionStatus = ref<ExecutionStatus | null>(null)
  const selectedTaskIds = ref<Set<string>>(new Set())
  const isModifying = ref<boolean>(false)
  const modificationDialog = ref<{
    visible: boolean
    taskId?: string
    type?: TaskModification['type']
  }>({
    visible: false
  })

  // 计算属性
  const currentTasks = computed(() => {
    if (!currentSessionId.value) return []
    const taskIds = sessionTasks.value.get(currentSessionId.value) || []
    const tasksArray = taskIds
      .map(id => tasks.value.get(id))
      .filter(Boolean) as Task[]
    return tasksArray.sort((a, b) => a.sequence - b.sequence)
  })

  const pendingTasks = computed(() => 
    currentTasks.value.filter(task => task.status === 'PENDING')
  )

  const inProgressTasks = computed(() => 
    currentTasks.value.filter(task => task.status === 'IN_PROGRESS')
  )

  const completedTasks = computed(() => 
    currentTasks.value.filter(task => task.status === 'COMPLETED')
  )

  const failedTasks = computed(() => 
    currentTasks.value.filter(task => task.status === 'FAILED')
  )

  const hasTasks = computed(() => currentTasks.value.length > 0)

  const canExecute = computed(() => 
    pendingTasks.value.length > 0 && !isExecuting.value
  )

  const isExecuting = computed(() => 
    executionStatus.value?.status === 'RUNNING' || 
    inProgressTasks.value.length > 0
  )

  const executionProgress = computed(() => {
    if (!hasTasks.value) return 0
    const total = currentTasks.value.length
    const completed = completedTasks.value.length
    return Math.round((completed / total) * 100)
  })

  // 私有方法
  const generateTaskId = (): string => {
    return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  // Session管理
  const setCurrentSession = (sessionId: string) => {
    currentSessionId.value = sessionId
    if (!sessionTasks.value.has(sessionId)) {
      sessionTasks.value.set(sessionId, [])
    }
  }

  const clearCurrentSession = () => {
    currentSessionId.value = null
    executionStatus.value = null
    selectedTaskIds.value.clear()
  }

  // 任务管理
  const addTask = (task: Omit<Task, 'id' | 'createdAt' | 'updatedAt'>) => {
    const newTask: Task = {
      ...task,
      id: generateTaskId(),
      createdAt: new Date(),
      updatedAt: new Date()
    }

    tasks.value.set(newTask.id, newTask)

    // 添加到会话任务列表
    if (newTask.sessionId) {
      const sessionTaskIds = sessionTasks.value.get(newTask.sessionId) || []
      sessionTaskIds.push(newTask.id)
      sessionTasks.value.set(newTask.sessionId, sessionTaskIds)
    }

    return newTask
  }

  const updateTask = (taskId: string, updates: Partial<Task>) => {
    const task = tasks.value.get(taskId)
    if (task) {
      const updatedTask = {
        ...task,
        ...updates,
        updatedAt: new Date()
      }
      tasks.value.set(taskId, updatedTask)
      return updatedTask
    }
    return null
  }

  const deleteTask = (taskId: string) => {
    const task = tasks.value.get(taskId)
    if (!task) return false

    tasks.value.delete(taskId)

    // 从会话任务列表中删除
    if (task.sessionId) {
      const sessionTaskIds = sessionTasks.value.get(task.sessionId) || []
      const updatedIds = sessionTaskIds.filter(id => id !== taskId)
      sessionTasks.value.set(task.sessionId, updatedIds)
    }

    selectedTaskIds.value.delete(taskId)
    return true
  }

  const clearTasks = (sessionId?: string) => {
    const targetSessionId = sessionId || currentSessionId.value
    if (!targetSessionId) return

    const taskIds = sessionTasks.value.get(targetSessionId) || []
    taskIds.forEach(taskId => {
      tasks.value.delete(taskId)
      selectedTaskIds.value.delete(taskId)
    })

    sessionTasks.value.set(targetSessionId, [])
  }

  // 执行状态更新
  const updateExecutionStatus = (status: ExecutionStatus) => {
    executionStatus.value = status
  }

  const handleTaskUpdate = (taskUpdate: Partial<Task> & { id: string }) => {
    updateTask(taskUpdate.id, taskUpdate)
  }

  // 重置方法
  const resetTasks = () => {
    tasks.value.clear()
    sessionTasks.value.clear()
    currentSessionId.value = null
    executionStatus.value = null
    selectedTaskIds.value.clear()
    isModifying.value = false
    modificationDialog.value = { visible: false }
  }

  return {
    // 状态
    tasks: readonly(tasks),
    sessionTasks: readonly(sessionTasks),
    currentSessionId: readonly(currentSessionId),
    executionStatus: readonly(executionStatus),
    selectedTaskIds: readonly(selectedTaskIds),
    isModifying: readonly(isModifying),
    modificationDialog: readonly(modificationDialog),

    // 计算属性
    currentTasks,
    pendingTasks,
    inProgressTasks,
    completedTasks,
    failedTasks,
    hasTasks,
    canExecute,
    isExecuting,
    executionProgress,

    // Session管理
    setCurrentSession,
    clearCurrentSession,

    // 任务管理
    addTask,
    updateTask,
    deleteTask,
    clearTasks,

    // 状态更新
    updateExecutionStatus,
    handleTaskUpdate,

    // 重置
    resetTasks
  }
})